const poster = {
	/**
	 * 绘制分享
	 **/
	drawShare(canvasId, userInfo, callback) {
		let winWidth = 375;
		let winHeight = 280;
		//获取绘图上下文 context
		let context = uni.createCanvasContext(canvasId, this)
		// 背景
		context.setFillStyle("#f7f7f7");
		context.fillRect(0, 0, winWidth, winHeight);
		//头像
		context.drawImage("/static/images/business-card/avatar.jpg", 15, 15, 177, 177)
		// 名片背景
		context.drawImage("/static/images/business-card/card-bg.png", 15, 15, 320, 177)
		//姓名
		context.textAlign = 'right'
		context.font = '800 20px PingFang SC'
		context.setFontSize(20)
		context.setFillStyle("#011128")
		context.fillText(userInfo.name, 324, 62)
		//职称
		context.textAlign = 'right'
		context.font = '300 12px PingFang SC'
		context.setFontSize(12)
		context.setFillStyle("#011128")
		context.fillText(userInfo.title, 324, 80)
		//电话
		context.textAlign = 'right'
		context.font = '300 12px PingFang SC'
		context.setFontSize(12)
		context.setFillStyle("#67707e")
		context.fillText(userInfo.phone, 305, 154)
		//电话图标
		context.drawImage("/static/images/business-card/phone.png", 310, 142, 12, 12)

		//公司
		context.textAlign = 'right'
		context.font = '300 12px PingFang SC'
		context.setFontSize(12)
		context.setFillStyle("#67707e")
		context.fillText(userInfo.company, 305, 178)
		//公司图标
		context.drawImage("/static/images/business-card/company.png", 310, 168, 12, 12)

		//查看按钮
		context.setFillStyle("rgb(66, 97, 140)");
		context.fillRect(106, 210, 145, 48);
		context.textAlign = 'center'
		context.setFontSize(20)
		context.setFillStyle("#ffffff")
		context.fillText("查看名片", 182, 240)

		context.draw(false, () => {
			poster.createPoster(canvasId, winWidth, winHeight, (res) => {
				callback && callback(res)
			})
		})
	},
	/**
	 * 绘制海报 
	 * @param canvasId 
	 * @param userInfo
	 **/
	drawPoster(canvasId, userInfo, callback) {
		let winWidth = 750;
		let winHeight = 700;
		//获取绘图上下文 context
		let context = uni.createCanvasContext(canvasId, this);
		//绘制名片主要区域
		// 背景
		context.setFillStyle("#f7f7f7");
		context.fillRect(0, 0, winWidth, winHeight);
		context.setFillStyle("#ffffff");
		context.fillRect(0, 440, winWidth, 310);
		//头像
		context.drawImage("/static/images/business-card/avatar.jpg", 30, 30, 382, 382)
		// 名片背景
		context.drawImage("/static/images/business-card/card-bg.png", 30, 30, 690, 382)
		//姓名
		context.textAlign = 'right'
		context.font = '800 40px PingFang SC'
		context.setFontSize(40)
		context.setFillStyle("#011128")
		context.fillText(userInfo.name, 695, 132)
		//职称
		context.textAlign = 'right'
		context.font = '300 24px PingFang SC'
		context.setFontSize(24)
		context.setFillStyle("#011128")
		context.fillText(userInfo.title, 695, 170)
		//电话
		context.textAlign = 'right'
		context.font = '300 24px PingFang SC'
		context.setFontSize(24)
		context.setFillStyle("#67707e")
		context.fillText(userInfo.phone, 665, 320)
		//电话图标
		context.drawImage("/static/images/business-card/phone.png", 670, 298, 24, 24)
		
		//公司
		context.textAlign = 'right'
		context.font = '300 24px PingFang SC'
		context.setFontSize(24)
		context.setFillStyle("#67707e")
		context.fillText(userInfo.company, 665, 370)
		//公司图标
		context.drawImage("/static/images/business-card/company.png", 670, 348, 24, 24)
		// 识别小程序二维码
		context.drawImage("/static/images/business-card/qrcode.jpg", 50, 480, 180, 180)

		context.textAlign = 'left'
		context.setFontSize(28)
		context.setFillStyle("#67707e")
		context.fillText("长按识别二维码", 270, 550)
		context.fillText("查看我的名片", 270, 600)

		context.draw(false, () => {
			poster.createPoster(canvasId, winWidth, winHeight, (res) => {
				callback && callback(res)
			})
		})
	},
	//生成海报图片(分享所需图片)
	createPoster(canvasId, winWidth, winHeight, callback) {
		var that = this;
		uni.canvasToTempFilePath({
			x: 0,
			y: 0,
			canvasId: canvasId,
			fileType: 'png',
			quality: 1,
			success: function(res) {
				callback && callback(res.tempFilePath)
			},
			fail() {
				callback && callback(false)
			}
		}, this)
	},
	modal: function(callback, confirmColor, confirmText) {
		uni.showModal({
			title: '提示',
			content: '您还没有开启相册权限，是否立即设置？',
			showCancel: true,
			cancelColor: "#555",
			confirmColor: "rgb(66, 97, 140)",
			confirmText: "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	// 将海报图片保存到本地
	saveImage(file) {
		//相册权限判断
		uni.authorize({
			scope: 'scope.writePhotosAlbum',
			success() {
				uni.saveImageToPhotosAlbum({
					filePath: file,
					success(res) {
						uni.showToast({
							title: '图片保存成功'
						})
					},
					fail(res) {
						uni.showToast({
							title: '图片保存失败',
							icon: 'none'
						})
					}
				})
			},
			fail() {
				poster.modal((res) => {
					if (res) {
						uni.openSetting({
							success(res) {
								console.log(res.authSetting)
							}
						});
					}
				})
			}
		})

	},
	//获取文本宽度(请先查看支持平台，App 端 2.8.12+ 支持)
	getTextWidth(text, context) {
		const metrics = context.measureText(text)
		return metrics.width || 0
	},
	//图片转成本地文件[同步执行]
	async getImage(url) {
		return await new Promise((resolve, reject) => {
			uni.downloadFile({
				url: url,
				success: res => {
					resolve(res.tempFilePath);
				},
				fail: res => {
					reject(false)
				}
			})
		})
	},
	//canvas多文字换行
	wrapText(text, width, context, rows = 2) {
		let txtArr = text.split('')
		let temp = ''
		let row = []
		for (let i = 0, len = txtArr.length; i < len; i++) {
			if (context.measureText(temp).width < width) {
				temp += txtArr[i]
			} else {
				i--
				row.push(temp)
				temp = ''
			}
		}
		row.push(temp)
		if (row.length > rows) {
			let rowCut = row.slice(0, rows);
			let rowPart = rowCut[rows - 1];
			let test = "";
			let empty = [];
			for (let j = 0, length = rowPart.length; j < length; j++) {
				if (context.measureText(test).width < width - 20) {
					test += rowPart[j];
				} else {
					break;
				}
			}
			empty.push(test);
			let group = empty[0] + "...";
			rowCut.splice(rows - 1, 1, group);
			row = rowCut;
		}
		return row
	},
	//删除已缓存文件，防止超出存储空间大小限制[同步执行]
	async removeSavedFile() {
		//使用前请先查看支持平台（其他方案：也可以先渲染出图片，当图片加载完成时执行相关方法）
		let count = 0;
		return await new Promise((resolve, reject) => {
			uni.getSavedFileList({
				success(res) {
					console.log(res)
					count = res.fileList.length;
					if (count > 0) {
						let num = 0;
						let list = res.fileList || []
						list.forEach(item => {
							console.log("执行删除文件。。。")
							uni.removeSavedFile({
								filePath: item.filePath,
								complete(res) {
									num++;
									if (num === count) {
										resolve(true)
									}
								}
							})
						})
					} else {
						resolve(true)
					}
				},
				fail() {
					reject(false)
					console.log("执行删除文件失败")
				}
			})
		})
	},
	//当服务器端返回图片base64时,转成本地文件[同步执行]
	async getImagebyBase64(base64) {
		return await new Promise((resolve, reject) => {
			const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
			let arrayBuffer = uni.base64ToArrayBuffer(bodyData)
			//getuuid：注意这里名称需要动态生成（名称相同部分机型会出现写入失败，显示的是上次生成的图片）
			const filePath = `${uni.env.USER_DATA_PATH}/${poster.getuuid()}.${format}`;
			uni.getFileSystemManager().writeFile({
				filePath,
				data: arrayBuffer,
				encoding: 'binary',
				success() {
					resolve(filePath);
				},
				fail() {
					reject(false)
				}
			})
		})
	},
	rpx2px(value) {
		let sys = uni.getSystemInfoSync()
		return sys.windowWidth / 750 * value
	},
	getuuid() {
		let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
			return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
		});
		return uuid;
	}
}

export default {
	drawShare: poster.drawShare,
	drawPoster: poster.drawPoster,
	getImage: poster.getImage,
	removeSavedFile: poster.removeSavedFile,
	getImagebyBase64: poster.getImagebyBase64,
	saveImage: poster.saveImage
};